<template>
  <el-dialog
    :model-value="drawerVisible"
    :destroy-on-close="true"
    :title="title"
    draggable
    :width="style.width"
    :class="`user-info-dialog ${props.projectId ? 'user-info-dialog-edit' : ''} ${
      stepPage === 1 ? 'user-info-dialog-startStep1' : 'user-info-dialog-startStep2'
    }`"
    :close-on-click-modal="false"
    @closed="handleClose"
    @close="handleClose"
    align-center="center"
  >
    <el-form ref="ruleFormRef" label-width="100px" label-suffix=" :" :rules="rules" :model="formData" label-position="top">
      <div class="startStep" v-show="stepPage === 1" :style="`height:${style.height}`">
        <div class="all-h info-form">
          <!-- <el-form-item label="订单" prop="orderCode">
            <el-input v-model="formData.orderCode" placeholder="请填写订单号" clearable></el-input> -->
          <!-- <el-select v-model="formData.orderId" placeholder="请选择订单" clearable>
              <el-option v-for="item in orderList" :key="item.code" :label="item.code" :value="item.id" />
            </el-select> -->
          <!-- </el-form-item> -->
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="formData.name" placeholder="请填写项目名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="项目编号" prop="code">
            <el-input v-model="formData.code" placeholder="请填写项目编号" clearable></el-input>
          </el-form-item>
          <el-form-item label="项目类型" prop="typeId">
            <el-select v-model="formData.typeId" placeholder="请选择项目类型" clearable>
              <el-option v-for="item in getDict('businessType')" :key="item.name" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="项目模板" prop="templateId" v-if="!props.projectId">
            <el-select v-model="formData.templateId" placeholder="请选择项目模板" clearable @change="changeTemplate">
              <el-option v-for="item in templateAll" :key="item.name" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户公司" prop="companyName">
            <el-input v-model="formData.companyName" placeholder="请填写客户公司" clearable></el-input>
          </el-form-item>
          <el-form-item label="终端客户公司" prop="companyFinalName">
            <el-input v-model="formData.companyFinalName" placeholder="请填写终端客户公司" clearable></el-input>
            <!-- <el-select v-model="formData.companyFinalId" placeholder="请选择终端客户公司" clearable @change="changeCompanyFinal">
              <el-option v-for="item in companyList" :key="item.name" :label="item.name" :value="item.id" />
            </el-select> -->
          </el-form-item>
          <el-form-item label="项目经理" prop="userId">
            <el-select v-model="formData.userId" placeholder="请选择项目经理" clearable filterable>
              <el-option v-for="item in viewUserList" :key="item.name" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="计划开始时间" prop="planStartTime">
            <el-date-picker
              v-model="formData.planStartTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择计划开始时间"
            />
          </el-form-item>
          <el-form-item label="	计划结束时间" prop="planEndTime">
            <el-date-picker
              v-model="formData.planEndTime"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择计划结束时间"
            />
          </el-form-item>
        </div>
        <div class="fan">
          <el-form-item label="项目描述" prop="description">
            <el-input
              type="textarea"
              v-model="formData.description"
              :autosize="{ minRows: 6 }"
              placeholder="请填写项目描述"
              clearable
            ></el-input>
          </el-form-item>
        </div>
      </div>
      <div v-show="stepPage === 2" :style="`height:${style.height}`">
        <Stage v-model:stage-list="formData.taskModels" :user-list="viewUserList" ref="stageListRef" />
      </div>
    </el-form>
    <template #footer>
      <div v-show="stepPage === 1">
        <el-button @click="emit('update:drawer-visible', false)"> 取消 </el-button>
        <el-button @click="nextFn"> 下一步</el-button>
      </div>
      <div v-show="stepPage === 2">
        <el-button @click="previewFn"> 上一步</el-button>
        <el-button type="primary" @click="handleSubmit"> {{ props.projectId ? "保存" : "创建" }} </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted, defineEmits } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { useDict } from "@/hooks/useDict";

import Stage from "./Stage.vue";
// api
// import { getCompanyList } from "@/api/modules/customer";
import { getTemplateType, getTemplateTaskModel, addProject, getProjectDetail, updateProject } from "@/api/modules/project";
import { getListAllUser } from "@/api/modules/sys";
// import { getOrderAvailable } from "@/api/modules/order";
// hook
const { getDict } = useDict(["businessType"]);
// 初始化数据
const props = defineProps({ drawerVisible: { type: Boolean, default: false }, projectId: { type: String, default: "" } });
const emit = defineEmits(["update:drawer-visible", "change"]);
// 变量定义
let style = reactive({
  width: "52%",
  height: "" // 36vh
});
let varTitle = ref(props.projectId ? "编辑" : "新增");
let title = ref(varTitle.value + "项目");
let formData = reactive({
  name: "",
  code: "",
  description: "",
  industryId: "",
  orderId: "",
  companyId: "",
  companyName: "",
  companyFinalId: "",
  companyFinalName: "",
  province: undefined,
  provinceCode: undefined,
  userId: "",
  city: undefined,
  cityCode: undefined,
  district: undefined,
  districtCode: undefined,
  countryId: undefined,
  countryName: undefined,
  addressed: [],
  address: "",
  typeId: "",
  hardwareNonStandard: false,
  hardwareContent: "",
  hardwareCycle: 0,
  softwareNonStandard: false,
  softwareContent: "",
  softwareCycle: 0,
  agvCount: "",
  progressId: "",
  status: "",
  planStartTime: "",
  planEndTime: "",
  startTime: "",
  endTime: "",
  templateId: "",
  statusDescription: "",
  taskModels: []
});
const rules = reactive({
  orderId: [{ required: false, message: "请选择订单" }],
  name: [{ required: true, message: "请填写项目名称" }],
  code: [{ required: true, message: "请填写项目编号" }],
  userId: [{ required: true, message: "请选择项目经理" }],
  typeId: [{ required: true, message: "请选择项目类型" }],
  planStartTime: [{ required: true, message: "请选择计划开始时间" }],
  planEndTime: [{ required: true, message: "请选择计划结束时间" }]
});
// let companyList = reactive([]);
let templateAll = reactive([]);
// let orderList = ref([]);
let stepPage = ref(1);
const ruleFormRef = ref();
const viewUserList = ref([]);
const stageListRef = ref(null);
// 事件
const changeTemplate = async templateId => {
  if (templateId) {
    if (formData.taskModels.length) {
      ElMessageBox.confirm("确认切换模板吗?", "温馨提示", { type: "warning" }).then(async () => {
        const { data } = await getTemplateTaskModel({ templateId });
        formData.taskModels.splice(0, formData.taskModels.length, ...data);
      });
    } else {
      const { data } = await getTemplateTaskModel({ templateId });
      formData.taskModels.splice(0, formData.taskModels.length, ...data);
    }
  } else {
    if (formData.taskModels.length) {
      ElMessageBox.confirm("确认切换模板吗?", "温馨提示", { type: "warning" }).then(() =>
        formData.taskModels.splice(0, formData.taskModels.length)
      );
    } else {
      formData.taskModels.splice(0, formData.taskModels.length);
    }
  }
};
const handleClose = () => {
  emit("update:drawer-visible", false);
};
const handleSubmit = () => {
  const stageListValue = stageListRef.value.getValue();
  formData.taskModels = stageListValue;
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      delete formData.addressed;
      delete formData.templateId;
      props.projectId ? await updateProject(formData) : await addProject(formData);
      ElMessage.success({ message: props.projectId ? `修改项目成功！` : `添加项目成功！` });
      emit("update:drawer-visible", false);
      emit("change", true);
    } catch (error) {
      console.log(error);
    }
  });
};
const nextFn = () => {
  style.width = "94.7%";
  style.height = "70vh";
  stepPage.value++;
};
const previewFn = () => {
  style.width = "52%";
  style.height = ""; // 36vh
  stepPage.value--;
};

/**信息获取*/

// 获取全部用户
const getListAllUserFn = async () => {
  const { data } = await getListAllUser();
  viewUserList.value = data;
};
// 获取全部公司
// const getCompanyListFn = async () => {
//   const { data } = await getCompanyList();
//   companyList.splice(0, companyList.length, ...data);
// };
// 获取全部模板
const getTemplateAllFn = async () => {
  const { data } = await getTemplateType({ id: "1820413471682985984" });
  templateAll.splice(0, templateAll.length, ...data);
};
// 获取项目详情
const getProjectDetailFn = async id => {
  const { data } = await getProjectDetail({ id });
  editInitData(data);
};
/**方法 */
const editInitData = data => {
  data.addressed = data.provinceCode
    ? [data.provinceCode, data.cityCode, data.districtCode].filter(item => item && item.trim())
    : [];
  Object.assign(formData, data);
  console.log(data);
};
// const getOrderAvailableFn = async () => {
//   const { data } = await getOrderAvailable({ projectId: props.projectId || undefined });
//   orderList.value = data;
// };
// const changeCompanyFinal = item => {
//   const companyLists = companyList.find(itm => itm.id === item);
//   formData.companyFinalName = companyLists?.name;
// };

onUnmounted(() => {});
onMounted(() => {
  // getCompanyListFn();
  getTemplateAllFn();
  getListAllUserFn();
  // getOrderAvailableFn();
  if (props.projectId) {
    getProjectDetailFn(props.projectId);
  }
});
</script>
<style lang="scss">
:deep(.user-info-dialog) {
  display: flex;
  height: 600px;
}
.user-info-dialog {
  .el-dialog__header {
    text-align: center;
  }

  border-radius: 8px;
  .info-container {
    height: 580px;
  }
  .info-form {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-gap: 0 30px;
    .el-select,
    .el-cascader,
    .el-input-number,
    .el-date-editor {
      width: 100%;
    }
  }
  .all-h {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-gap: 0 30px;
    width: 100%;
    .el-select,
    .el-cascader,
    .el-input-number,
    .el-date-editor {
      width: 100%;
    }
  }
  .fan {
    .title {
      margin-bottom: 10px;
      font-size: 16px;
      font-weight: 400;
      color: #333333;
    }
    .table {
      margin-bottom: 20px;
    }
  }
  .title {
    margin-bottom: 10px;
  }
  .form-item {
    margin: 0;
  }
}
.user-info-dialog-startStep1 {
  // .el-dialog__body {
  //   padding: 20px;
  // }
}
.user-info-dialog-startStep2 {
  .el-dialog__header {
    margin-bottom: 0;
  }
}
.user-info-dialog-edit {
  .all-h {
    grid-template-columns: 1fr 1fr 1fr 1fr;
  }
}
</style>
